package com.baymax.test.scene.internal.key

import android.graphics.Color
import android.util.TypedValue
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.FrameLayout
import android.widget.TextView
import androidx.annotation.IdRes
import com.baymax.lib.key.KeySession
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

interface ViewFinder {

    fun findViewById(@IdRes id: Int): View
}

abstract class WatchTvIndicatorImpl(finder: ViewFinder) : WatchTvKeyTransFormer() {

    val content by lazy { finder.findViewById(android.R.id.content) }
    private val tv by lazy { inflateIndicator(content) }

    override fun onPickStart(keySession: KeySession) {
        val sp = keySession.snapShot()
        content.post {
            tv.text = sp.toKeyCodeStr()
            tv.visibility = View.VISIBLE
        }
    }

    private fun inflateIndicator(content: View): TextView {
        var tv = content.findViewById<TextView>(com.baymax.test.scene.R.id.watch_tv_indicator)
        if (tv == null) {
            val res = content.resources
            tv = TextView(content.context)
            tv.setBackgroundColor((Color.parseColor("#AB000000")))
            tv.setTextColor(Color.WHITE)
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 44f)
            val px160 = 160
            val lp = FrameLayout.LayoutParams(px160, px160)
            lp.marginEnd = 120
            lp.topMargin = 60
            lp.gravity = Gravity.TOP or Gravity.END
            tv.gravity = Gravity.CENTER
            (content as ViewGroup).addView(tv, lp)
        }
        return tv
    }

    override fun onPickEnd(keySession: KeySession) {
        val sp = keySession.snapShot()
        content.post {
            tv.text = sp.toKeyCodeStr()
        }
        content.postDelayed({
            tv.visibility = View.GONE
        }, 1000)
    }

    override fun onPickSuccess(keySession: KeySession, list: List<KeyEvent>) {
    }

    override fun onPickContinue(keySession: KeySession) {
        val sp = keySession.snapShot()
        content.post {
            tv.text = sp.toKeyCodeStr()
        }
    }

    private fun List<KeyEvent>.toKeyCodeStr(): String {
        val s = this.dropWhile { it.keyCode == KeyEvent.KEYCODE_0 }
            .joinToString("") { KeyEvent.keyCodeToString(it.keyCode).removePrefix("KEYCODE_") }
            .format("%3s")
        return String.format("%3s", s).replace(" ", "0")
    }

}

